<?php
/**
 * usefull functions
 * @desc for 360cps 
 */
define('APP_PATH', dirname(dirname(__FILE__))) ;
require_once APP_PATH . 'models/cps360_login.php' ;
require_once APP_PATH . 'models/cps360_order.php' ;
require_once APP_PATH . 'models/cps360_xml.php' ;
class Cps360_Api {
	
	static public $INTERFACE_PARAMS = array(
		'redirect' => array('bid','qihoo_id','url','from_url','active_time','ext','qid','qmail','qname','sign','verify'),
		'order' => array('bid','order_ids','start_time','end_time','updstart_time','updend_time','last_order_id','active_time','sign'),
		'check' => array('bid','bill_month','last_order_id','active_time','sign'),
	);
	
	public function __construct(){
		
	}
	
	/**
	 * Redirect Interface
	 */	
	public function redirect()
	{
		$params = self::params('redirect');
		$cookie_domain = CPS360_Conf::CPS_COOKIE_DOMAIN ;
		//Cookie infos and setting
		$cookies = array(
			'id' => '360cps',
			'qihoo_id' => $params['qihoo_id'],
			'ext' => $params['ext'],
			'qid' => $params['qid'],
			'qmail' => $params['qmail'],
			'qname' => $params['qname'],
		);
		$cookie_setting = array(
			'name' => CPS360_Conf::CPS_COOKIE_NAME,
			'value' => self::encrypt($cookies),
			'expires' => time() + (86400 * CPS360_Conf::CPS_COOKIE_RD),
			'path' => '/',
		);
		setcookie($cookie_setting['name'] , $cookie_setting['value'] , $cookie_setting['expires'] ,$cookie_setting['path']) ;
		
		//check
		$sigh_flag 		= self::check_sign($params ,'redirect') ;
		$active_flag	= self::check_expire($params['active_time']) ;
		if(!$sigh_flag['isok'] || !$active_flag['isok']){
			$data_report = $params;
			$data_report['userip'] = self::get_ip();
			$data_report['useragent'] = $_SERVER['HTTP_USER_AGENT'];
			self::http_request(CPS360_Conf::CPS_REPORT_URL,'post',$data_report);
			$params['qid'] = $params['qmail'] = $params['qname'] = false;
		}
		//Auto login
		if ($params['qid']>0){
			Cps360_Login::auto_login($params['qid'], $params['qname'], $params['qmail']) ;
		}
		//redirect
		if($params['url'] && (strpos(CPS360_Conf::CPS_COOKIE_DOMAIN, $params['url']) !== false)){
			$url = $params['url'] ;
		}else {
			$url = CPS360_Conf::CPS_BASE_URL ;
		}
		header('Location:' . $url) ;
	}
	
	// query interface
	public function order()
	{
		$params = self::params('order');
		$orderobj = new CPS360_Order() ;
		$orderxml = new Cps360_Xml() ;
		
		$sigh_flag 		= self::check_sign($params ,'order') ;
		$active_flag	= self::check_expire($params['active_time']) ;
		if(!$sigh_flag['isok'] || !$active_flag['isok']){
			echo $sigh_flag['errinfo'] . ' ' .$active_flag['errinfo'] ;
			exit;
		}
		
		//choose condition
		if($params['order_ids']){
			$result = $orderobj->order_by_ids($params['order_ids']);
		}elseif($params['start_time'] && $params['end_time']){
			$result = $orderobj->order_by_time($params['start_time'],$params['end_time'],$params['last_order_id']);
		}elseif($params['updstart_time'] && $params['updend_time']){
			$result = $orderobj->order_by_updtime($params['updstart_time'],$params['updend_time'],$params['last_order_id']);
		}else{
			$result = array();
		}
		
		//output result
		echo $orderxml->format_data($result);
	}
	
	//Check out interface
	public function check()
	{
		$params = self::params('check');
		$orderobj = new CPS360_Order() ;
		$orderxml = new Cps360_Xml() ;
		$sigh_flag 		= self::check_sign($params ,'check') ;
		$active_flag	= self::check_expire($params['active_time']) ;
		if(!$sigh_flag['isok'] || !$active_flag['isok']){
			echo $sigh_flag['errinfo'] . ' ' .$active_flag['errinfo'] ;
			exit;
		}
		//get check out orders
		$result = $orderobj->check_by_month($params['bill_month'],$params['last_order_id']);
		echo $orderxml->format_data($result , 'check') ;
	}
	
	/**
	 * check whether the request is expire
	 * @param unknown_type $active_time
	 */
	
	static private function check_expire($active_time = 0)
	{
		if(abs(time() - $active_time) > CPS360_Conf::CPS_EXPIRE){
			$result = array('isok' => false,'errinfo' => 'Expire Request');
		}else{
			$result = array('isok' => true,'errinfo' => '');
		}
		return $result;
	}
	
	/**
	 * check if match the sign flag
	 * @param mixed $params
	 * @param string $type
	 */
	static private function check_sign($params ,$type="redirect")
	{
		$resign = CPS360_conf::CPS_BID.'#'.$params['active_time'].'#'.CPS360_conf::CPS_CPKEY;
		if($type == 'redirect'){
			$resign .= '#'.$params['qid'].'#'.$params['qmail'].'#'.$params['qname'];
		}
		$resign = md5($resign);
		if ($params['sign'] && $params['sign'] !== $resign){
			$result = array('isok' => false,'errinfo' => '验证失败');
		}else{
			$result = array('isok' => true ,'errinfo' => '');
		}
		return $result;
	}
	
	
	static public function params($type='')
	{
		if(empty($type)||!array_key_exists($type, self::$INTERFACE_PARAMS)){
			return array() ;
		}
		$key_names = self::$INTERFACE_PARAMS[$type] ;
		foreach ($key_names as $key){
			if(isset($_POST[$key])){
				$params[$key] = $_POST[$key];
			}elseif(CPS360_Conf::CPS_DEBUG && isset($_GET[$key])){
				$params[$key] = $_GET[$key];
			}else{
				$params[$key] = null;
			}
		}
		return $params ;
	}
	
	//encrypt
	static public function encrypt($info)
	{
		$str = serialize($info);
		$md5 = md5(CPS360_conf::CPS_CPKEY.$str);
		return urlencode($md5.$str);
	}
	
	//decrypt
	static public function decrypt($str)
	{
		if(!$str) return false;
		$str = urldecode($str);
		$md5 = substr($str,0,32);
		$str = substr($str,32);
		$remd5 = md5(CPS360_Conf::CP_KEY.$str);
		if($md5 !== $remd5) return false;
		return unserialize($str);
	}
	
	//
	static public function http_request($url,$method = 'get',$data = array())
	{
		$ch = curl_init();
		curl_setopt_array($ch,array(
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_FOLLOWLOCATION => false,
				CURLOPT_USERAGENT => '',
				CURLOPT_TIMEOUT => 10,
				CURLOPT_URL => $url,
			)
		);

		//Post
	    if($method == 'post') {
	        $postdata = array();
	        foreach($data as $key => $value){
	            $postdata[] = urlencode($key).'='.urlencode($value);
	        }
			curl_setopt_array($ch,array(
					CURLOPT_POST => true,
					CURLOPT_POSTFIELDS => implode('&',$postdata),
				)
			);
	    }

		curl_exec($ch);
		curl_close($ch);
	}
	
	public function get_ip()
	{
		$ip = '';
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
}